import React, { Component } from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { Form, Input, Button, Radio, message, Upload, Icon } from "antd";
import { LOGIN_LINK, MY_LINK } from "../actions/types.js";
import { checkAuth } from "../actions/index";
import axios from "axios";
const FormItem = Form.Item;
const RadioGroup = Radio.Group;

function beforeUpload(file) {
  const isAllow = (file.type === 'image/jpeg' || file.type === 'image/png' || file.type=== 'image/svg+xml');
  // console.log(file.type);return;
  if (!isAllow) {
    message.error('请上传png或jpg格式或svg格式的图片');
  }
  const isLt2M = file.size  < 2 * 1024 * 1024;
  if (!isLt2M) {
    message.error('图片大小不能超过2MB');
  }
  return isAllow && isLt2M;
}
class UserInfo extends Component {
  state={imageUrl:""}
  componentDidMount(){
    this.props.checkAuth();
    if(this.props.user){
      this.props.form.setFields({
        user_name: {value: this.props.user.userName},
        diff: {value: this.props.user.diff},
        sex: {value: this.props.user.sex},
      });
      this.setState({imageUrl:this.props.user.img})
    }
  }
  componentWillUpdate(nextProps){
    if(this.props.user === null && nextProps.user !== null){
      this.props.form.setFields({
        user_name: {value: nextProps.user.userName},
        diff: {value: nextProps.user.diff},
        sex: {value: nextProps.user.sex},
      });
      this.setState({imageUrl:nextProps.user.img})
    }
  }
  render() {
    if (this.props.type === "register") {
      return (
        <div>
          <div style={{ paddingLeft: "30px", margin: "18px 0" }}>
            请完善你的个人资料
          </div>
          {this.renderRegisterForm()}
        </div>
      );
    } else {
      return (
        <section style={{ padding: "30px 10px", background: "#fff" }}>
          <div className="top-title">
            <i
              className="fa fa-angle-left back"
              onClick={() => this.props.history.go(-1)}
            />
            完善个人资料
          </div>
          {this.renderUserInfoForm()}
        </section>
      );
    }
  }
  renderRegisterForm(){
    const { getFieldDecorator } = this.props.form;
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">点击上传头像</div>
      </div>
    );
    const imageUrl = this.state.imageUrl;
    return(
      <Form onSubmit={this.handleFinalRegister} className="login-form">
        <FormItem style={{marginBottom:"12px"}}>
          <Upload
            name="file"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action="/Tgh/data/head_img_upload"
            beforeUpload={beforeUpload}
            onChange={this.handleChangeIcon}
          >
            {imageUrl ? <img src={`/images/${imageUrl}`} width="100%" alt="点击上传" /> : uploadButton}
          </Upload>
        </FormItem>
        <FormItem>
          {getFieldDecorator("user_name", {
            rules: [{ required: true, message: "请输入姓名" }]
          })(
            <Input
              addonBefore={
                <span style={{ padding: "0 4px 0 12px" }}>姓名</span>
              }
              style={{ width: "100%" }}
              placeholder="请输入真实姓名"
            />
          )}
        </FormItem>
        <FormItem>
          {getFieldDecorator("diff", {
            rules: [{ required: true, message: "请输入差点" }]
          })(
            <Input
              type="number"
              addonBefore={
                <span style={{ padding: "0 4px 0 12px" }}>差点</span>
              }
              style={{ width: "100%" }}
              placeholder="请输入您的差点"
            />
          )}
        </FormItem>
        <FormItem>
          {getFieldDecorator("sex")(
            <RadioGroup>
              <Radio value="man">男</Radio>
              <Radio value="woman">女</Radio>
            </RadioGroup>
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            htmlType="submit"
            className="login-form-button"
          >
            完成
          </Button>
          <Link
            to={LOGIN_LINK}
            style={{
              color: "#A9A9A9",
              textAlign: "right",
              display: "block"
            }}
          >
            跳过>
          </Link>
        </FormItem>
      </Form>
    )
  }
  // 用户信息的表单填写
  renderUserInfoForm(){
    const { getFieldDecorator } = this.props.form;
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">点击上传头像</div>
      </div>
    );
    const imageUrl = this.state.imageUrl;
    return(
      <Form onSubmit={this.handleFinalRegister} className="login-form">
        <FormItem style={{marginBottom:"12px"}}>
          <Upload
            name="file"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action="/Tgh/data/head_img_upload"
            beforeUpload={beforeUpload}
            onChange={this.handleChangeIcon}
          >
            {imageUrl ? <img src={`/images/${imageUrl}`} width="100%" alt="点击上传" /> : uploadButton}
          </Upload>
        </FormItem>
        <FormItem>
          {getFieldDecorator("user_name", {
            rules: [{ required: true, message: "请输入姓名" }]
          })(
            <Input
              addonBefore={
                <span style={{ padding: "0 4px 0 12px" }}>姓名</span>
              }
              style={{ width: "100%" }}
              placeholder="请输入真实姓名"
            />
          )}
        </FormItem>
        <FormItem>
          {getFieldDecorator("diff", {
            rules: [{ required: true, message: "请输入差点" }]
          })(
            <Input
              type="number"
              addonBefore={
                <span style={{ padding: "0 4px 0 12px" }}>差点</span>
              }
              style={{ width: "100%" }}
              placeholder="请输入您的差点"
            />
          )}
        </FormItem>
        <FormItem>
          {getFieldDecorator("sex")(
            <RadioGroup>
              <Radio value="man">男</Radio>
              <Radio value="woman">女</Radio>
            </RadioGroup>
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            htmlType="submit"
            className="login-form-button"
          >
            完成
          </Button>
        </FormItem>
      </Form>
    )
  }
  handleFinalRegister = e => {
    e.preventDefault();
    let telphone = "";
    if(this.props.type === "register"){
      telphone = this.props.telphone
    }else{
      telphone = this.props.user.telphone
    }
    this.props.form.validateFields((err, values) => {
      // console.log(values);
      if (err) {
        console.log(err);
        return;
      } else {
        if (!values.sex) {
          message.warning("请选择你的性别");
          return;
        }
        // 修改个人信息
        let params = {};
        params["img"] = this.state.imageUrl;
        params["user_name"] = values.user_name;
        params["diff"] = values.diff;
        params["sex"] = values.sex;
        params["telphone"] = telphone;
        axios.get(`/Tgh/data/register_information_data`, {params:params}).then(res => {
          if(this.props.type === "register"){
            this.props.history.push(LOGIN_LINK);
            message.success("填写个人信息成功,请登陆");
          }else{
            this.props.history.push(MY_LINK);
            message.success("修改个人信息成功");
          }
        });
      }
    });
  };
  // icon的上传
  handleChangeIcon = (info) => {
    console.log(info);
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      this.setState({
        imageUrl:info.file.response.img_name,
        loading: false,
      })
    }
  }
}
function mapStateToProps(state) {
  // console.log('state is',state);
  const { status, error, user } = state.auth;
  return { user, status, error };
}
export default connect(mapStateToProps, {checkAuth})(Form.create()(UserInfo));
